﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace PCR.Logic
{
    using PCR.Base;

    /// <summary>
    /// User privilege xml database
    /// </summary>
    internal class XmlPrivilege : IPrivilegeAccess
    {
        protected System.Xml.XmlDocument _doc;
        protected string _filename;

        /// <summary>
        /// Xml tag definition
        /// </summary>
        static readonly string User_Tag = "User";
        static readonly string UserName_Tag = "UserName";
        static readonly string Password_Tag = "Password";
        static readonly string Default_Username = "admin";
        static readonly string Default_Password = "admin";
        
        // 默认密钥向量
        private static byte[] Encypt_Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        private static string Private_EncyptKey = "12345678";
        
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="doc">xml document</param>
        /// <param name="filename">xml filename, used to store data to the file</param>
        public XmlPrivilege(System.Xml.XmlDocument doc,
            string filename)
        {
            System.Diagnostics.Debug.Assert(doc != null);
            System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(filename));

            this._doc = doc;
            this._filename = filename;
        }

        /// <summary>
        /// Get the user instance
        /// </summary>
        /// <returns>Return the current user interface</returns>
        public IUser GetUser()
        {
            System.Xml.XmlNode nodeRoot = this._doc.SelectSingleNode("PCRConfig");
            System.Diagnostics.Debug.Assert(nodeRoot != null, "PCRConfig xml tag can not be empty!");

            System.Xml.XmlNode nodeUser = nodeRoot.SelectSingleNode(User_Tag);
            if (nodeUser == null)
            {
                // Node not existed, create a default user and save it
                if (!UpdateUser(Default_Username, Default_Password))
                    return null;
            }

            return GetUserFromFile(); ;
        }

        /// <summary>
        /// Update the user information
        /// </summary>
        /// <param name="userName">User name</param>
        /// <param name="password">Password</param>
        public bool UpdateUser(string userName, string password)
        {
            System.Xml.XmlNode nodeRoot = this._doc.SelectSingleNode("PCRConfig");
            System.Diagnostics.Debug.Assert(nodeRoot != null, "PCRConfig xml tag can not be empty!");

            System.Xml.XmlNode nodeUser = nodeRoot.SelectSingleNode(User_Tag);
            if (nodeUser == null)
            {
                // Create a new node and attached to root
                nodeUser = this._doc.CreateElement(User_Tag);
                nodeRoot.AppendChild(nodeUser);
            }
            else
                nodeUser.RemoveAll();

            // Create username and password attributes
            System.Xml.XmlAttribute attr = this._doc.CreateAttribute(UserName_Tag);
            attr.Value = EncryptDES(userName, Private_EncyptKey);
            nodeUser.Attributes.Append(attr);

            attr = this._doc.CreateAttribute(Password_Tag);
            attr.Value = EncryptDES(password, Private_EncyptKey);
            nodeUser.Attributes.Append(attr);

            Save();
            return true;
        }

        private void Save()
        {
            this._doc.Save(this._filename);
        }

        protected IUser GetUserFromFile()
        {
            System.Xml.XmlNode nodeRoot = this._doc.SelectSingleNode("PCRConfig");
            System.Diagnostics.Debug.Assert(nodeRoot != null, "PCRConfig xml tag can not be empty!");

            System.Xml.XmlNode nodeUser = nodeRoot.SelectSingleNode(User_Tag);
            System.Diagnostics.Debug.Assert(nodeUser != null);

            // Create a user interface
            IUser user = new User();

            // Get the username and password attributes
            System.Xml.XmlAttribute attr = nodeUser.Attributes[UserName_Tag];
            System.Diagnostics.Debug.Assert(attr != null);
            user.UserName = DecryptDES(attr.Value, Private_EncyptKey);
            
            attr = nodeUser.Attributes[Password_Tag];
            System.Diagnostics.Debug.Assert(attr != null);
            user.Password = DecryptDES(attr.Value, Private_EncyptKey);

            return user;
        }

        /**/
        /**/
        /**/
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        private static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Encypt_Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        /**/
        /**/
        /**/
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        private static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Encypt_Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
    }
}
